<template>
  <el-dialog title="选择分类" center :visible="dialogVisible" width="30%" @open="load">
      <el-tree
        :data="categories"
        @node-click="checkChange"
        :check-on-click-node="true"
        >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="title">{{ data.name }}</span>
          <span>
            <el-button
              type="text"
              size="mini"
              @click="() => append(data)">
              <i class="el-icon-plus"></i>
            </el-button>
            <el-button
              type="text"
              size="mini"
              v-if="!data.isRoot"
              @click="() => remove(node, data)">
              <i class="el-icon-delete"></i>
            </el-button>
          </span>
        </span>
      </el-tree>
      <div slot="footer" class="dialog-footer" align="right">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
  </el-dialog>
</template>

<script>
import api from '@/api'
export default {
  mounted () {
    this.$bus.$on('toggle-category-dialog', (visible) => {
      this.dialogVisible = true
    })
  },
  data () {
    return {
      tempCategory: null,
      dialogVisible: false,
      categories: [{
        name: '所有分类',
        isRoot: true,
        children: []
      }]
    }
  },
  methods: {
    append (data) {
      // if (!data.children) {
      //   this.$set(data, 'children', [])
      // }
      // data.children.push(newChild);
    },

    remove (node, data) {
      const parent = node.parent
      const children = parent.data.children || parent.data
      const index = children.findIndex(d => d.id === data.id)
      children.splice(index, 1)
    },
    checkChange (data) {
      if (data.id) {
        this.tempCategory = data
      } else {
        this.tempCategory = null
      }
    },
    confirm () {
      this.dialogVisible = false
      this.$emit('on-confirm', this.tempCategory)
    },
    load () {
      api.getAllCategories().then(api.commonResp((success, data) => {
        if (success) {
          console.log(JSON.stringify(data))
          this.categories[0].children = data
          console.log(JSON.stringify(this.categories))
        } else {
          this.$message.error(data)
        }
      }))
    }
  }
}
</script>

<style scoped lang="less">
  .custom-tree-node {
    .title {
      margin-right: 20px;
    }
  }
</style>
